package LimitedTimeGame.Day_0130;

/**
 * @author zxc
 * @date 2023/01/30 11:49
 **/

import LinkedList.ListNode;

/**
 * 题目 ：合并两个链表
 * 题目详述 ：
 * 给你两个链表list1 和list2，它们包含的元素分别为n个和m个。
 * 请你将list1中下标从 a 到 b 的全部节点都删除，并将list2接在被删除节点的位置。
 *
 * 提示：
 * 3 <= list1.length <= 104
 * 1 <= a <= b < list1.length - 1
 * 1 <= list2.length <= 104
 */
public class MergeInBetween {
    public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
        // list2链表的头节点;
        ListNode list2Head = list2;
        // 遍历长度为m的list2链表，来获取list2的尾节点;
        while(list2.next != null){
            list2 = list2.next;
        }
        // list2链表的尾节点;
        ListNode list2Tail = list2;
        // 使用node节点来保存list1链表的头结点;
        ListNode node = list1;
        ListNode list1AtoPrevious = new ListNode(0);
        ListNode list1B = new ListNode(0);
        int k = 0;
        while(k <= b){
            ListNode temp = node.next;
            if(k == b){
                list1B = temp;
                node.next = null;
            }
            if(k == a - 1){
                list1AtoPrevious = node;
                list1AtoPrevious.next = null;
            }
            node = temp;
            k++;
        }
        list1AtoPrevious.next = list2Head;
        list2Tail.next = list1B;
        return list1;
    }
    public class ListNode {
          int val;
          ListNode next;
          ListNode() {}
          ListNode(int val) { this.val = val; }
          ListNode(int val, ListNode next) { this.val = val; this.next = next; }
      }
}
